<template>
  <div class="data-export-dialog">
    <el-dialog
      title="数据导出"
      :visible.sync="visible"
      width="600px"
      :before-close="handleClose"
    >
      <div class="export-content">
        <!-- 导出类型选择 -->
        <div class="export-section">
          <h3>选择导出类型</h3>
          <el-radio-group v-model="exportType" class="export-type-group">
            <el-radio label="basic">基础信息</el-radio>
            <el-radio label="statistics">统计数据</el-radio>
            <el-radio label="installs">安装记录</el-radio>
            <el-radio label="events">事件记录</el-radio>
            <el-radio label="comprehensive">综合报告</el-radio>
          </el-radio-group>
        </div>

        <!-- 时间范围选择 -->
        <div class="export-section">
          <h3>选择时间范围</h3>
          <el-radio-group v-model="dateRangeType" @change="handleDateRangeChange">
            <el-radio label="today">今天</el-radio>
            <el-radio label="week">最近7天</el-radio>
            <el-radio label="month">最近30天</el-radio>
            <el-radio label="custom">自定义范围</el-radio>
          </el-radio-group>
          
          <div v-if="dateRangeType === 'custom'" class="custom-date-range">
            <el-date-picker
              v-model="customDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </div>
        </div>

        <!-- 导出格式选择 -->
        <div class="export-section">
          <h3>选择导出格式</h3>
          <el-radio-group v-model="exportFormat">
            <el-radio label="excel">Excel (.xlsx)</el-radio>
            <el-radio label="csv">CSV (.csv)</el-radio>
            <el-radio label="json">JSON (.json)</el-radio>
          </el-radio-group>
        </div>

        <!-- 高级选项 -->
        <div class="export-section" v-if="showAdvancedOptions">
          <h3>高级选项</h3>
          <el-checkbox-group v-model="advancedOptions">
            <el-checkbox label="includeDeleted">包含已删除数据</el-checkbox>
            <el-checkbox label="includeTestData">包含测试数据</el-checkbox>
            <el-checkbox label="anonymizeData">匿名化处理</el-checkbox>
            <el-checkbox label="splitByDate">按日期分文件</el-checkbox>
          </el-checkbox-group>
        </div>

        <!-- 导出预览 -->
        <div class="export-section" v-if="showPreview">
          <h3>导出预览</h3>
          <div class="preview-info">
            <p><strong>预计数据量：</strong>{{ estimatedRecords }} 条记录</p>
            <p><strong>预计文件大小：</strong>{{ estimatedFileSize }}</p>
            <p><strong>生成时间：</strong>{{ estimatedTime }}</p>
          </div>
        </div>

        <!-- 导出进度 -->
        <div class="export-section" v-if="exporting">
          <h3>导出进度</h3>
          <el-progress 
            :percentage="exportProgress" 
            :status="exportStatus"
            :text-inside="true"
            :stroke-width="20"
          ></el-progress>
          <p class="export-status">{{ exportStatusText }}</p>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="startExport" 
          :loading="exporting"
          :disabled="!canExport"
        >
          {{ exporting ? '导出中...' : '开始导出' }}
        </el-button>
        <el-button 
          v-if="downloadUrl" 
          type="success" 
          @click="downloadFile"
          icon="el-icon-download"
        >
          下载文件
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { exportDataApi } from '@/api/apps'

export default {
  name: 'DataExportDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    appId: {
      type: String,
      required: true
    },
    appName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      exportType: 'comprehensive',
      dateRangeType: 'week',
      customDateRange: [],
      exportFormat: 'excel',
      advancedOptions: [],
      showAdvancedOptions: false,
      showPreview: false,
      exporting: false,
      exportProgress: 0,
      exportStatus: '',
      exportStatusText: '',
      downloadUrl: '',
      estimatedRecords: 0,
      estimatedFileSize: '0 KB',
      estimatedTime: '约 1-2 分钟',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24)
              end.setTime(end.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  computed: {
    canExport() {
      return !this.exporting && this.appId && this.exportType && this.exportFormat
    },
    
    dateRange() {
      const end = new Date()
      let start = new Date()
      
      switch (this.dateRangeType) {
        case 'today':
          start.setHours(0, 0, 0, 0)
          break
        case 'week':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          break
        case 'month':
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          break
        case 'custom':
          if (this.customDateRange && this.customDateRange.length === 2) {
            return {
              start: this.customDateRange[0],
              end: this.customDateRange[1]
            }
          }
          return null
      }
      
      return { start: start.toISOString().split('T')[0], end: end.toISOString().split('T')[0] }
    }
  },
  watch: {
    exportType() {
      this.updatePreview()
    },
    dateRangeType() {
      this.updatePreview()
    },
    exportFormat() {
      this.updatePreview()
    },
    customDateRange() {
      this.updatePreview()
    }
  },
  methods: {
    handleClose() {
      if (this.exporting) {
        this.$confirm('导出正在进行中，确定要取消吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.resetExport()
          this.$emit('update:visible', false)
        }).catch(() => {})
      } else {
        this.resetExport()
        this.$emit('update:visible', false)
      }
    },
    
    handleDateRangeChange() {
      if (this.dateRangeType === 'custom') {
        this.customDateRange = []
      }
    },
    
    updatePreview() {
      if (!this.dateRange) return
      
      // 模拟估算数据量
      const days = this.calculateDays(this.dateRange.start, this.dateRange.end)
      let recordsPerDay = 0
      
      switch (this.exportType) {
        case 'basic':
          recordsPerDay = 1
          break
        case 'statistics':
          recordsPerDay = 24 // 每小时一条统计
          break
        case 'installs':
          recordsPerDay = Math.floor(Math.random() * 500) + 100 // 100-600安装/天
          break
        case 'events':
          recordsPerDay = Math.floor(Math.random() * 2000) + 500 // 500-2500事件/天
          break
        case 'comprehensive':
          recordsPerDay = Math.floor(Math.random() * 3000) + 1000 // 1000-4000综合/天
          break
      }
      
      this.estimatedRecords = days * recordsPerDay
      
      // 估算文件大小
      let bytesPerRecord = 0
      switch (this.exportFormat) {
        case 'excel':
          bytesPerRecord = 512 // Excel格式较大
          break
        case 'csv':
          bytesPerRecord = 128 // CSV格式较小
          break
        case 'json':
          bytesPerRecord = 256 // JSON格式中等
          break
      }
      
      const totalBytes = this.estimatedRecords * bytesPerRecord
      this.estimatedFileSize = this.formatFileSize(totalBytes)
      
      // 估算时间
      const minutes = Math.ceil(this.estimatedRecords / 1000) // 每1000条记录约1分钟
      this.estimatedTime = minutes <= 1 ? '约 1 分钟' : `约 ${minutes} 分钟`
      
      this.showPreview = true
    },
    
    calculateDays(start, end) {
      const startDate = new Date(start)
      const endDate = new Date(end)
      const diffTime = Math.abs(endDate - startDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      return Math.max(diffDays, 1)
    },
    
    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    async startExport() {
      if (!this.canExport) return
      
      this.exporting = true
      this.exportProgress = 0
      this.exportStatus = ''
      this.exportStatusText = '正在准备导出...'
      this.downloadUrl = ''
      
      try {
        // 模拟导出进度
        const steps = [
          { progress: 10, text: '正在验证权限...' },
          { progress: 25, text: '正在查询数据...' },
          { progress: 50, text: '正在处理数据...' },
          { progress: 75, text: '正在生成文件...' },
          { progress: 90, text: '正在打包文件...' },
          { progress: 100, text: '导出完成！' }
        ]
        
        for (const step of steps) {
          await this.delay(800) // 模拟处理时间
          this.exportProgress = step.progress
          this.exportStatusText = step.text
          
          if (step.progress === 100) {
            this.exportStatus = 'success'
            
            // 调用实际的导出API
            const exportData = {
              app_id: this.appId,
              export_type: this.exportType,
              date_range: this.dateRange,
              format: this.exportFormat,
              advanced_options: this.advancedOptions,
              filename: `${this.appName || '应用数据'}_${this.getCurrentDate()}_${this.exportType}.${this.exportFormat}`
            }
            
            const res = await exportDataApi(exportData)
            if (res.code === 200 && res.data.download_url) {
              this.downloadUrl = res.data.download_url
              this.exportStatusText = '文件已生成，点击下载按钮获取文件'
            } else {
              throw new Error(res.msg || '导出失败')
            }
          }
        }
        
      } catch (error) {
        this.exportStatus = 'exception'
        this.exportStatusText = '导出失败：' + error.message
        this.$message.error('数据导出失败：' + error.message)
      } finally {
        this.exporting = false
      }
    },
    
    downloadFile() {
      if (!this.downloadUrl) return
      
      // 创建临时下载链接
      const link = document.createElement('a')
      link.href = this.downloadUrl
      link.download = `${this.appName || '应用数据'}_${this.getCurrentDate()}_${this.exportType}.${this.exportFormat}`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('文件下载已开始')
    },
    
    resetExport() {
      this.exporting = false
      this.exportProgress = 0
      this.exportStatus = ''
      this.exportStatusText = ''
      this.downloadUrl = ''
      this.showPreview = false
    },
    
    delay(ms) {
      return new Promise(resolve => setTimeout(resolve, ms))
    },
    
    getCurrentDate() {
      return new Date().toISOString().split('T')[0]
    }
  }
}
</script>

<style scoped>
.data-export-dialog {
  width: 100%;
}

.export-content {
  padding: 0 10px;
}

.export-section {
  margin-bottom: 25px;
}

.export-section h3 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.export-type-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.custom-date-range {
  margin-top: 15px;
}

.preview-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.preview-info p {
  margin: 8px 0;
  color: #606266;
}

.preview-info strong {
  color: #303133;
}

.export-status {
  margin-top: 10px;
  text-align: center;
  color: #606266;
  font-size: 14px;
}

@media (max-width: 768px) {
  .export-type-group {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .export-section h3 {
    font-size: 14px;
  }
}
</style>